package com.ys.controller.web.storage;

import com.ys.config.MenuId;
import com.ys.dto.SubGridConfigDto;
import com.ys.entity.storage.*;
import com.ys.enume.storage.TccFbaLogisticsMethodEnum;
import com.ys.service.storage.FbaInboundApiService;
import com.ys.service.sys.CommonApiService;
import com.ys.vo.R;
import com.ys.vo.W;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: fxz
 * @CreateTime: 2024-12-04
 * @Description: FBA计划单WEB
 * @Version: 1.5
 */
@Controller
@RequestMapping("/web/storage/tccFbaPlan")
public class WebTccFbaPlanController {
    private static final Logger logger = LoggerFactory.getLogger(WebTccFbaPlanController.class);


    private final Long MENU_ID = MenuId.TCC_FbaPlan;
    private final Long MENU_ID1 = MenuId.TCC_FbaPlanX;

    private final Long MENU_IDWl = MenuId.TCC_FbaLogisticsMethodJh;

    private final Long MENU_IDFee = MenuId.TCC_FbaFeeDetailsJh;

    @Autowired
    private CommonApiService<TccFbaPlan> commonApiService;

    @Autowired
    private CommonApiService<TccFbaLogisticsMethod> commonApiServiceWl;

    @Autowired
    private CommonApiService<TccFbaFeeDetails> commonApiServiceFee;

    private final ReentrantLock lock = new ReentrantLock();//同步锁


    /*
     * 新增
     */
    @GetMapping("/toAdd")
    public String toAdd(Model model, HttpServletRequest request, HttpServletResponse response, String goodsIds) {
        try {
            TccFbaPlan entity = new TccFbaPlan();
            lock.lock(); // 加锁
            String bid = commonApiService.getCommonNextBid(MENU_ID1);
            entity.setBid(bid);
            entity.setDeclarationState(2);
            entity.setEvenlyBoxNum(0);
            entity.setCreateTime(new Date());
            lock.unlock(); // 释放锁

            Map<String, Object> extraParam = new HashMap<>();
            //关联数据
            extraParam.put("declarationStateName", "空");
            // 子列表配置信息
            SubGridConfigDto subGridConfig = commonApiService.getSubGrid(MENU_ID1,new ArrayList<>());
            commonApiService.toAdd(model, entity, MENU_ID1, extraParam, subGridConfig);
            return "storage/tccFbaPlan/toAdd";
        }catch (Exception e) {
            logger.error("详情页面出错：",e.getMessage(),e);
            return W.error(model, e.getMessage());
        }finally {
            try {
                lock.unlock(); // 确保释放锁
            }catch (Exception e){}
        }
    }

    /*
     * 编辑
     */
    @GetMapping("/toEdit")
    public String toEdit(Model model, HttpServletRequest request, HttpServletResponse response, String bid) {
        try {
            Map<String, Object> tccFbaPlan = new TccFbaPlan().setBid(bid)
             .addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                    .addField("FORMAT(A.createTime, 'yyyy-MM-dd HH:mm:ss') createTime1")//创建时间
                    .addField("CASE WHEN  A.EffectStock = 1 THEN FORMAT(A.UpdateTime, 'yyyy-MM-dd HH:mm:ss') ELSE FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') END auditingTime1")//审核时间
                    .addField("case when A.declarationState = 0 then '否' else '是' end as declarationStateName")
             .addLeftJoin("TCC_FbaLogisticsMethod C ON C.sourceBid = A.bid AND C.sourceType = 0")
                    .addField("C.logsticsWay,C.cck,C.vck,C.estimatedDayFrom,C.estimatedDayTo,C.transportationCn transportationTypeCn,C.logsticsWayId,C.remark logsticsRemark")
                    .addField("case when C.nameLogsticsClearance = 0 then '自税' else '包税' end as nameLogsticsClearanceName")//清关方式
             .addLeftJoin("TCC_FbaFeeDetails D ON D.sourceBid = A.bid AND D.sourceType = 0")
                    .addField("D.priceTranPredict,D.priceTranCalWeight,D.priceExtraPredict")
                    .queryFirstMap();
            List<Map<String, Object>> itemList = new TccFbaPlanItem()
                    .addField("(CONVERT(varchar(19), cast(A.lengthPackage as float)) + '*' + CONVERT(varchar(19), cast(A.widthPackage as float))  + '*' + CONVERT(varchar(19), cast(A.heightPackage as float))) packageSize")
                    .addField("case when A.declarationItemState = 0 then '否' else '是' end as declarationItemStateName")
                    .setBidFbaPlan(bid).queryMap();
            // 子列表配置信息
            SubGridConfigDto subGridConfig = commonApiService.getSubGrid(MENU_ID1,itemList);

            commonApiService.toEdit(model, Long.valueOf(tccFbaPlan.get("id").toString()), new TccFbaPlan(), MENU_ID1, tccFbaPlan, subGridConfig);
            return "storage/tccFbaPlan/toEdit";
        }catch (Exception e) {
            logger.error("编辑页面出错：",e.getMessage(),e);
            return W.error(model, e.getMessage());
        }
    }

    /*
     * 物流方式 - 详情
     */
    @GetMapping("/toEditWl")
    public String toEditWl(Model model, HttpServletRequest request, HttpServletResponse response, String bid) {
        try {
            Map<String, Object> tccFbaLogisticsMethod = new TccFbaLogisticsMethod().setSourceBid(bid)
                    .addField("case when A.nameLogsticsClearance = 0 then '自税' else '包税' end as nameLogsticsClearanceName")//清关方式
                    .addField("case when A.divisionalRule = 0 then '0.1kg进1kg' when A.divisionalRule = 1 then '0.5kg进1kg' else '不约分' end as divisionalRuleName")//约分规则
                    .addField("FORMAT(A.createTime, 'yyyy-MM-dd HH:mm:ss') createTime1")//创建时间
                    .addLeftJoin("TCC_FbaPlan B ON B.Bid = A.SourceBid AND A.SourceType = 0")
                    .addField("B.bid bid,B.Vgsbm vgsbm,B.VgsJc vgsJc ")
                    .setSourceType(TccFbaLogisticsMethodEnum.SourceType.FBAPLAN.value).queryFirstMap();
            commonApiServiceWl.toEdit(model, Long.valueOf(tccFbaLogisticsMethod.get("id").toString()), new TccFbaLogisticsMethod(), MENU_IDWl, tccFbaLogisticsMethod, null);
            return "storage/tccFbaPlan/toEditWl";
        }catch (Exception e) {
            logger.error("物流方式详情页面出错：",e.getMessage(),e);
            return W.error(model, e.getMessage());
        }
    }

    /*
     * 预估费用详情
     */
    @GetMapping("/toEditFee")
    public String toEditFee(Model model, HttpServletRequest request, HttpServletResponse response, String bid) {
        try {
            Map<String, Object> tccFbaFeeDetails = new TccFbaFeeDetails().setSourceBid(bid)
                    .setSourceType(TccFbaLogisticsMethodEnum.SourceType.FBAPLAN.value)
                    .addLeftJoin("TCC_FbaPlan B ON B.Bid = A.SourceBid AND A.SourceType = 0")
                    .addField("B.bid bid,B.Vgsbm vgsbm,B.VgsJc vgsJc,B.ShopName shopName")
                    .addLeftJoin("YS_ProcInst P ON P.Bid = B.Bid ")
                    .addField("FORMAT(A.createTime, 'yyyy-MM-dd HH:mm:ss') createTime1")//创建时间
                    .addLeftJoin("TCC_FbaLogisticsMethod C ON C.SourceBid = B.Bid AND C.SourceType = 0")
                    .addField("C.LogsticsWay logsticsWay,C.Cck cck,C.nameLogsticsClearance nameLogsticsClearance")
                    .addField("C.transportationCn transportationCn,C.remark remarkWl,C.vck vck,C.clearanceOpeAmount clearanceOpeAmount,C.jfFee jfFee")
                    .addField("C.pzFee pzFee,C.czFee czFee")
                    .addField("C.additionalBilling")
                    .addField("case when (A.numProName - C.FreeProNameNum) < 0 then 0 else A.numProName - C.FreeProNameNum end as numProNameSf")
                    .addField("case when C.nameLogsticsClearance = 0 then '自税' else '包税' end as nameLogsticsClearanceName")//清关方式
                    .addField("CAST('预估物流费（总）=预估计重费（￥）+预估附加费（￥）+清关服务费(￥)' AS VARCHAR(255))  priceTranPredictSm")
                    .queryFirstMap();
            commonApiServiceFee.toEdit(model, Long.valueOf(tccFbaFeeDetails.get("id").toString()), new TccFbaFeeDetails(), MENU_IDFee, tccFbaFeeDetails, null);
            return "storage/tccFbaPlan/toEditWl";
        }catch (Exception e) {
            logger.error("预估费用详情页面出错：",e.getMessage(),e);
            return W.error(model, e.getMessage());
        }
    }

    /*
     * 计划审核-按SKU自动发货
     */
    @GetMapping("/flow")
    public String flow(Model model, HttpServletRequest request, HttpServletResponse response, String bid) {
        try {
            model.addAttribute("bid",bid);
            return "storage/tccFbaPlan/toFlow";
        }catch (Exception e) {
            logger.error("计划审核页面出错：",e.getMessage(),e);
            return W.error(model, e.getMessage());
        }
    }

    /*
     * 计划审核-按SKU自动发货-详情
     */
    @GetMapping("/flowDetail")
    public String flowDetail(Model model, HttpServletRequest request, HttpServletResponse response, String bid,String shipmentId) {
        try {
            model.addAttribute("bid",bid);
            model.addAttribute("shipmentId",shipmentId);
            return "storage/tccFbaPlan/toFlowDetail";
        }catch (Exception e) {
            logger.error("计划审核页面出错：",e.getMessage(),e);
            return W.error(model, e.getMessage());
        }
    }
}

